<template>
	<div id="add-picture-batch-view">
		<div class="header">
			<h2>批量创建图片</h2>
			<p class="subtitle">通过关键词批量抓取网络图片并自动创建</p>
		</div>

		<!-- 图片信息表单 -->
		<a-card class="form-container" :bordered="false">
			<a-form name="formData" layout="vertical" :model="formData" @finish="handleSubmit">
				<a-row :gutter="24">
					<a-col :xs="24" :sm="12">
						<a-form-item
							name="searchText"
							label="搜索关键词"
							:rules="[{ required: true, message: '请输入搜索关键词!' }]"
						>
							<a-input
								v-model:value="formData.searchText"
								placeholder="请输入搜索关键词，如：风景、动物、建筑等"
								allow-clear
								size="large"
							/>
						</a-form-item>
					</a-col>
					<a-col :xs="24" :sm="12">
						<a-form-item name="count" label="抓取数量" :rules="[{ required: true, message: '请输入抓取数量!' }]">
							<a-input-number
								v-model:value="formData.count"
								placeholder="建议1-20张"
								style="width: 100%"
								size="large"
								:min="1"
								:max="50"
								allow-clear
							/>
						</a-form-item>
					</a-col>
				</a-row>

				<a-row :gutter="24">
					<a-col :xs="24" :sm="12">
						<a-form-item name="offset" label="偏移量">
							<a-input-number
								v-model:value="formData.offset"
								placeholder="从第几张图片开始抓取，默认从第0张开始"
								style="width: 100%"
								size="large"
								:min="0"
								:max="1000"
								allow-clear
							/>
						</a-form-item>
					</a-col>
					<a-col :xs="24" :sm="12">
						<a-form-item name="namePrefix" label="图片名称前缀">
							<a-input
								v-model:value="formData.namePrefix"
								placeholder="默认使用搜索关键词，会自动补充序号"
								allow-clear
								size="large"
							/>
						</a-form-item>
					</a-col>
				</a-row>

				<a-row :gutter="24">
					<a-col :xs="24" :sm="12">
						<a-form-item name="category" label="分类">
							<a-auto-complete
								v-model:value="formData.category"
								placeholder="选择或输入分类"
								:options="filteredCategoryOptions"
								allow-clear
								size="large"
								@search="onCategorySearch"
								@select="onCategorySelect"
							/>
						</a-form-item>
					</a-col>
					<a-col :xs="24" :sm="12">
						<a-form-item name="tags" label="标签">
							<a-select
								v-model:value="formData.tags"
								mode="multiple"
								placeholder="选择标签"
								:options="filteredTagOptions"
								allow-clear
								show-search
								size="large"
								:filter-option="false"
								@search="onTagSearch"
								@select="onTagSelect"
								@deselect="onTagDeselect"
							/>
						</a-form-item>
					</a-col>
				</a-row>

				<a-form-item class="submit-container">
					<a-button type="primary" html-type="submit" :loading="loading" class="submit-btn">
						<template #icon>
							<CloudDownloadOutlined />
						</template>
						{{ loading ? '正在抓取图片...' : '开始批量抓取' }}
					</a-button>
				</a-form-item>
			</a-form>
		</a-card>

		<!-- 使用说明 -->
		<a-card title="使用说明" class="help-container" :bordered="false">
			<a-row :gutter="16">
				<a-col :xs="24" :sm="8">
					<div class="help-item">
						<InfoCircleOutlined class="help-icon" />
						<h4>抓取规则</h4>
						<p>系统会根据关键词从网络抓取相关图片，建议使用具体、明确的关键词以获得更好的结果。</p>
					</div>
				</a-col>
				<a-col :xs="24" :sm="8">
					<div class="help-item">
						<WarningOutlined class="help-icon warning" />
						<h4>数量限制</h4>
						<p>单次最多抓取50张图片，建议每次抓取1-20张以确保质量。抓取过多可能导致处理时间较长。</p>
					</div>
				</a-col>
				<a-col :xs="24" :sm="8">
					<div class="help-item">
						<CheckCircleOutlined class="help-icon success" />
						<h4>自动处理</h4>
						<p>抓取的图片会自动添加到图片库中，您可以在首页查看和管理这些图片。</p>
					</div>
				</a-col>
			</a-row>
		</a-card>
	</div>
</template>

<script setup lang="ts">
import { uploadPictureByBatchUsingPost, listPictureTagCategoryUsingGet } from '@/api/pictureController'
import { message } from 'ant-design-vue'
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { CloudDownloadOutlined, InfoCircleOutlined, WarningOutlined, CheckCircleOutlined } from '@ant-design/icons-vue'

const router = useRouter()

const formData = reactive<API.PictureUploadByBatchRequest>({})
const loading = ref(false)

// 分类和标签相关数据
const categoryOptions = ref<{ value: string; label: string }[]>([])
const tagOptions = ref<{ value: string; label: string }[]>([])
const filteredCategoryOptions = ref<{ value: string; label: string }[]>([])
const filteredTagOptions = ref<{ value: string; label: string }[]>([])

// 防抖定时器
let categorySearchTimer: number | null = null
let tagSearchTimer: number | null = null

// 搜索值
const categorySearchValue = ref('')
const tagSearchValue = ref('')

// === 分类相关功能 ===
// 分类搜索（带防抖）
const onCategorySearch = (searchText: string) => {
	categorySearchValue.value = searchText

	// 清除之前的定时器
	if (categorySearchTimer) {
		clearTimeout(categorySearchTimer)
	}

	// 设置新的防抖定时器
	categorySearchTimer = setTimeout(() => {
		filterCategoryOptions(searchText)
	}, 300) // 300ms 防抖延迟
}

// 过滤分类选项
const filterCategoryOptions = (searchText: string) => {
	if (!searchText) {
		filteredCategoryOptions.value = categoryOptions.value
	} else {
		const searchLower = searchText.toLowerCase()
		filteredCategoryOptions.value = categoryOptions.value.filter((option) => {
			// 支持包含匹配、大小写不敏感
			return option.label.toLowerCase().includes(searchLower) || option.value.toLowerCase().includes(searchLower)
		})
	}
}

// 分类选择
const onCategorySelect = (value: string) => {
	formData.category = value
	categorySearchValue.value = ''
}

// === 标签相关功能 ===
// 标签搜索（带防抖）
const onTagSearch = (searchText: string) => {
	tagSearchValue.value = searchText

	// 清除之前的定时器
	if (tagSearchTimer) {
		clearTimeout(tagSearchTimer)
	}

	// 设置新的防抖定时器
	tagSearchTimer = setTimeout(() => {
		filterTagOptions(searchText)
	}, 300) // 300ms 防抖延迟
}

// 过滤标签选项
const filterTagOptions = (searchText: string) => {
	if (!searchText) {
		filteredTagOptions.value = tagOptions.value
	} else {
		const searchLower = searchText.toLowerCase()
		// 过滤出匹配的标签选项
		filteredTagOptions.value = tagOptions.value.filter(
			(option) => option.label.toLowerCase().includes(searchLower) || option.value.toLowerCase().includes(searchLower)
		)
	}
}

// 标签选择
const onTagSelect = (value: string) => {
	tagSearchValue.value = ''
}

// 标签取消选择
const onTagDeselect = (value: string) => {
	// 清除搜索关键词
	if (tagSearchValue.value === value) {
		tagSearchValue.value = ''
	}
}

// 获取分类和标签选项
const getTagCategoryOptions = async () => {
	try {
		const res = await listPictureTagCategoryUsingGet()

		if (res.data.code === 0 && res.data.data) {
			// 设置分类选项
			categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
				return {
					value: data,
					label: data,
				}
			})

			// 设置标签选项
			tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
				return {
					value: data,
					label: data,
				}
			})

			// 初始化过滤选项为全部选项
			filteredCategoryOptions.value = [...categoryOptions.value]
			filteredTagOptions.value = [...tagOptions.value]
		} else {
			// 处理后端返回的错误
			message.error('获取分类标签列表失败: ' + res.data.message)
		}
	} catch (error) {
		message.error('获取分类标签列表失败')
	}
}

// 提交表单
const handleSubmit = async () => {
	if (!formData.searchText) {
		message.error('请输入搜索关键词!')
		return
	}

	if (!formData.count || formData.count < 1) {
		message.error('请输入有效的抓取数量!')
		return
	}

	loading.value = true

	try {
		const res = await uploadPictureByBatchUsingPost({
			...formData,
		})

		// 操作成功
		if (res.data.code === 0 && res.data.data) {
			message.success(`创建成功！共抓取了 ${res.data.data} 张图片`)
			// 跳转到主页
			router.push({
				path: '/',
			})
		} else {
			message.error('创建失败：' + res.data.message)
		}
	} catch (error: any) {
		console.error('批量创建失败', error)
		message.error('创建失败：' + error.message)
	} finally {
		loading.value = false
	}
}

// 组件挂载时获取数据
onMounted(() => {
	getTagCategoryOptions()
})
</script>

<style scoped lang="scss">
#add-picture-batch-view {
	max-width: 1000px;
	margin: 0 auto;
	padding: 24px;

	.header {
		text-align: center;
		margin-bottom: 32px;

		h2 {
			font-size: 28px;
			font-weight: 600;
			color: #1f2937;
			margin-bottom: 8px;
		}

		.subtitle {
			font-size: 16px;
			color: #6b7280;
			margin: 0;
		}
	}

	.form-container {
		margin-bottom: 24px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
		border-radius: 12px;

		.ant-form-item {
			margin-bottom: 24px;
		}

		.ant-form-item-label > label {
			font-weight: 500;
			color: #374151;
		}

		.submit-container {
			margin-top: 32px;
			margin-bottom: 0;
			text-align: center;
		}

		.submit-btn {
			width: 300px;
			height: 48px;
			font-size: 16px;
			font-weight: 500;
			border-radius: 8px;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			border: none;
			box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
			transition: all 0.3s ease;

			&:hover {
				transform: translateY(-2px);
				box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
			}

			&:active {
				transform: translateY(0);
			}

			&[loading] {
				background: #6b7280;
			}
		}
	}

	.help-container {
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
		border-radius: 12px;

		.help-item {
			text-align: center;
			padding: 20px 16px;

			.help-icon {
				font-size: 32px;
				color: #3b82f6;
				margin-bottom: 12px;
				display: block;

				&.warning {
					color: #f59e0b;
				}

				&.success {
					color: #10b981;
				}
			}

			h4 {
				font-size: 16px;
				font-weight: 600;
				color: #1f2937;
				margin-bottom: 8px;
			}

			p {
				font-size: 14px;
				color: #6b7280;
				line-height: 1.5;
				margin: 0;
			}
		}
	}

	// 响应式设计
	@media (max-width: 768px) {
		padding: 16px;

		.header h2 {
			font-size: 24px;
		}

		.submit-btn {
			width: 100%;
		}

		.help-item {
			margin-bottom: 24px;
		}
	}

	// 输入框样式优化
	:deep(.ant-input) {
		border-radius: 8px;
		border: 1px solid #d1d5db;

		&:focus {
			border-color: #3b82f6;
			box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
		}
	}

	:deep(.ant-input-number) {
		border-radius: 8px;
		border: 1px solid #d1d5db;

		&:focus-within {
			border-color: #3b82f6;
			box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
		}
	}

	:deep(.ant-select) {
		.ant-select-selector {
			border-radius: 8px;
			border: 1px solid #d1d5db;
		}

		&.ant-select-focused .ant-select-selector {
			border-color: #3b82f6;
			box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
		}
	}

	:deep(.ant-auto-complete) {
		.ant-select-selector {
			border-radius: 8px;
			border: 1px solid #d1d5db;
		}

		&.ant-select-focused .ant-select-selector {
			border-color: #3b82f6;
			box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
		}
	}
}
</style>
